package com.mdd.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.base.page.PageValidate;
import com.mdd.common.core.PageResult;
import com.mdd.common.enums.DeptModelEnum;
import com.mdd.common.util.ListUtils;
import com.mdd.system.RtAdminThreadLocal;
import com.mdd.system.entity.SystemAuthAdmin;
import com.mdd.system.entity.SystemAuthDept;
import com.mdd.system.mapper.SystemAuthAdminMapper;
import com.mdd.system.mapper.SystemAuthDeptMapper;
import com.mdd.system.service.ISystemAuthAdminService;
import com.mdd.system.service.ISystemAuthDeptService;
import com.mdd.system.validate.SystemAdminCreateValidate;
import com.mdd.system.validate.SystemDeptCreateValidate;
import com.mdd.system.validate.SystemDeptSearchValidate;
import com.mdd.system.validate.SystemDeptUpdateValidate;
import com.mdd.system.vo.SystemAuthAdminInformVo;
import com.mdd.system.vo.SystemAuthDeptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统部门服务实现类
 */
@Service
public class SystemAuthDeptServiceImpl extends ServiceImpl<SystemAuthDeptMapper,SystemAuthDept> implements ISystemAuthDeptService {

    @Resource
    SystemAuthDeptMapper systemAuthDeptMapper;
    @Resource
    SystemAuthAdminMapper systemAuthAdminMapper;
    @Resource
    ISystemAuthAdminService iSystemAuthAdminService;
    /**
     * 岗位所有
     *
     * @author fzr
     * @return List<SystemAuthDeptVo>
     */
    @Override
    public List<SystemAuthDeptVo> all() {
        String deptCode = RtAdminThreadLocal.get("deptCode").toString();
        List<SystemAuthDept> systemAuthDeptList = systemAuthDeptMapper.selectList(new QueryWrapper<SystemAuthDept>()
                .gt("pid", 0)
                .likeRight("dept_code",deptCode)
                .orderByDesc((Arrays.asList("sort", "id"))));

        List<SystemAuthDeptVo> list = new ArrayList<>();
        for (SystemAuthDept systemAuthDept : systemAuthDeptList) {
            SystemAuthDeptVo vo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept, vo);

            list.add(vo);
        }

        return list;
    }

    /**
     *  部门列表
     *
     * @author fzr
     * @param searchValidate 搜索参数
     * @return JSONArray
     */
    @Override
    public JSONArray list(SystemDeptSearchValidate searchValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        QueryWrapper<SystemAuthDept> queryWrapper = new QueryWrapper<>();

        if (!"1".equals(systemAuthAdmin.getDeptCode())) {
            queryWrapper.likeRight("dept_code", systemAuthAdmin.getDeptCode());
        }
        queryWrapper.orderByDesc(Arrays.asList("sort", "id"));
        queryWrapper.select(SystemAuthDept.class, info ->
                !"is_delete".equals(info.getColumn()) &&
                !"delete_time".equals(info.getColumn()));

        systemAuthDeptMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:name:str",
                "=:isStop@is_stop:int"
        });

        List<SystemAuthDept> systemAuthDeptList = systemAuthDeptMapper.selectList(queryWrapper);

        List<SystemAuthDeptVo> list = new LinkedList<>();
        for (SystemAuthDept systemAuthDept : systemAuthDeptList) {
            SystemAuthDeptVo vo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept, vo);
            list.add(vo);
        }

        JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
        return ListUtils.listToTree(jsonArray, "id", "pid", "children");
    }
    @Override
    public PageResult<SystemAuthDeptVo> listPage(PageValidate pageValidate , SystemDeptSearchValidate searchValidate) {
        String deptId = RtAdminThreadLocal.get("deptIds").toString();
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        MPJQueryWrapper<SystemAuthDept> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.select("id,pid,type,name,duty,mobile,sort,is_stop,is_delete,create_time,update_time,delete_time,dept_code");
        queryWrapper.eq("pid",deptId);
        if(Objects.nonNull(searchValidate.getType())) {
            queryWrapper.eq("type", searchValidate.getType());
        }
        //queryWrapper.likeRight("dept_code",deptCode);
        queryWrapper.orderByDesc(Arrays.asList("sort", "id"));

        systemAuthDeptMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:name:str",
                "=:isStop@is_stop:int"
        });

        IPage<SystemAuthDept> iPage = systemAuthDeptMapper.selectJoinPage(new Page<>(page, limit),
                SystemAuthDept.class,queryWrapper);
        List<SystemAuthDeptVo> list = new LinkedList<>();
        for(SystemAuthDept systemAuthDept : iPage.getRecords()){
            SystemAuthDeptVo systemAuthDeptVo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept,systemAuthDeptVo);
            generateSystemAuthDeptVo(systemAuthDeptVo);
            list.add(systemAuthDeptVo);
        }

        return   PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public PageResult<SystemAuthDeptVo> listOP(PageValidate pageValidate , SystemDeptSearchValidate searchValidate) {
        String deptId = RtAdminThreadLocal.get("deptIds").toString();
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        MPJQueryWrapper<SystemAuthDept> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.select("id,pid,type,name,duty,mobile,sort,is_stop,is_delete,create_time,update_time,delete_time,dept_code");
        queryWrapper.eq("pid",deptId);
        queryWrapper.eq("type","1");
        //queryWrapper.likeRight("dept_code",deptCode);       queryWrapper.orderByDesc(Arrays.asList("sort", "id"));

        systemAuthDeptMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:name:str",
                "=:isStop@is_stop:int"
        });

        IPage<SystemAuthDept> iPage = systemAuthDeptMapper.selectJoinPage(new Page<>(page, limit),
                SystemAuthDept.class,queryWrapper);
        List<SystemAuthDeptVo> list = new LinkedList<>();
        for(SystemAuthDept systemAuthDept : iPage.getRecords()){
            SystemAuthDeptVo systemAuthDeptVo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept,systemAuthDeptVo);
            list.add(systemAuthDeptVo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }
    @Override
    public PageResult<SystemAuthDeptVo> listCP(PageValidate pageValidate , SystemDeptSearchValidate searchValidate) {
        String deptId = RtAdminThreadLocal.get("deptIds").toString();
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();
        MPJQueryWrapper<SystemAuthDept> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.select("id,pid,type,name,duty,mobile,sort,is_stop,is_delete,create_time,update_time,delete_time,dept_code");
        queryWrapper.eq("pid",deptId);
        queryWrapper.eq("type","2");
        //queryWrapper.likeRight("dept_code",deptCode);
        queryWrapper.orderByDesc(Arrays.asList("sort", "id"));

        systemAuthDeptMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:name:str",
                "=:isStop@is_stop:int"
        });

        IPage<SystemAuthDept> iPage = systemAuthDeptMapper.selectJoinPage(new Page<>(page, limit),
                SystemAuthDept.class,queryWrapper);
        List<SystemAuthDeptVo> list = new LinkedList<>();
        for(SystemAuthDept systemAuthDept : iPage.getRecords()){
            SystemAuthDeptVo systemAuthDeptVo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept,systemAuthDeptVo);
            list.add(systemAuthDeptVo);
        }

        return   PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public List<SystemAuthDeptVo> claimList(SystemAuthAdminInformVo systemAuthAdmin) {
        List<SystemAuthDept> systemAuthDepts=  systemAuthDeptMapper.selectList(new LambdaQueryWrapper<SystemAuthDept>()
                .in(SystemAuthDept::getModel, DeptModelEnum.CITY_PARTNER.getCode(),DeptModelEnum.VEHICLE_MANAGE.getCode()));
        List<SystemAuthDeptVo> systemAuthDeptVos = new ArrayList<>();
        systemAuthDepts.forEach(systemAuthDept -> {
            SystemAuthDeptVo systemAuthDeptVo = new SystemAuthDeptVo();
            BeanUtils.copyProperties(systemAuthDept,systemAuthDeptVo);
            systemAuthDeptVos.add(systemAuthDeptVo);

        });

        return systemAuthDeptVos;
    }

    @Override
    public List<SystemAuthDeptVo> allocationList(SystemAuthAdminInformVo systemAuthAdmin) {
        SystemAuthDept adminDept = systemAuthDeptMapper.selectById(systemAuthAdmin.getDeptIds());
        //当前层级为平台时 查询智能车管和城市合伙人
        if(adminDept.getType().equals(0)){
            return claimList(systemAuthAdmin);
        }else {
            List<SystemAuthDept> systemAuthDepts = systemAuthDeptMapper.selectList(new LambdaQueryWrapper<SystemAuthDept>()
                    .eq(SystemAuthDept::getPid, systemAuthAdmin.getDeptIds()));
            List<SystemAuthDeptVo> systemAuthDeptVos = new ArrayList<>();
            systemAuthDepts.forEach(systemAuthDept -> {
                SystemAuthDeptVo systemAuthDeptVo = new SystemAuthDeptVo();
                BeanUtils.copyProperties(systemAuthDept, systemAuthDeptVo);
                systemAuthDeptVos.add(systemAuthDeptVo);

            });
            return systemAuthDeptVos;
        }
    }

    /**
     * 部门详情
     *
     * @author fzr
     * @param id 主键
     * @return SystemDeptVo
     */
    @Override
    public SystemAuthDeptVo detail(Long id) {
        SystemAuthDept systemAuthDept = systemAuthDeptMapper.selectOne(
                new QueryWrapper<SystemAuthDept>()
                        .select(SystemAuthDept.class, info ->
                                !"is_delete".equals(info.getColumn()) &&
                                        !"delete_time".equals(info.getColumn()))
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(systemAuthDept, "部门已不存在!");

        SystemAuthDeptVo vo  = new SystemAuthDeptVo();
        BeanUtils.copyProperties(systemAuthDept, vo);

        return vo;
    }

    /**
     * 部门新增
     *
     * @author fzr
     * @param createValidate 参数
     */
    @Transactional
    @Override
    public void add(SystemDeptCreateValidate createValidate, SystemAuthAdminInformVo systemAuthAdmin) {
        SystemAuthDept model = new SystemAuthDept();
        model.setPid(systemAuthAdmin.getDeptIds());
        model.setName(createValidate.getName());
        model.setDuty(createValidate.getDuty());
        model.setMobile(createValidate.getMobile());
        model.setSort(createValidate.getSort());
        model.setIsStop(createValidate.getIsStop());
        //部门类型 0、平台1、代理（OP）2、商户（CP）3、部门
        model.setType(3);
        SystemAuthDept pDept = systemAuthDeptMapper.selectById(systemAuthAdmin.getDeptIds());
        systemAuthDeptMapper.insert(model);
        model.setDeptCode(pDept.getDeptCode()+ "," + model.getId().toString());
        systemAuthDeptMapper.updateById(model);
    }

    @Transactional
    @Override
    public void addOP(SystemDeptCreateValidate createValidate) {
        SystemAuthDept model = new SystemAuthDept();
        if (!Objects.isNull(createValidate.getPid())){
            model.setPid(createValidate.getPid());
        }else {
            model.setPid(1L);
        }
        model.setName(createValidate.getName());
        model.setDuty(createValidate.getDuty());
        model.setMobile(createValidate.getMobile());
        model.setSort(createValidate.getSort());
        //type 1 OP
        model.setType(1);
        //级别0 默认城市OP
        model.setModel(DeptModelEnum.CITY_PARTNER.getCode());
        model.setIsStop(createValidate.getIsStop());
        systemAuthDeptMapper.insert(model);
        SystemAuthDept pDept;
        if (Objects.isNull(model.getPid())){
            pDept = systemAuthDeptMapper.selectById(1);
        }else {
            pDept = systemAuthDeptMapper.selectById(model.getPid());
        }
        model.setDeptCode(pDept.getDeptCode()+ "," + model.getId().toString());
        systemAuthDeptMapper.updateById(model);
        //将OP负责人添加成企业负责人
        SystemAdminCreateValidate systemAdminCreateValidate=new SystemAdminCreateValidate();
        systemAdminCreateValidate.setUsername(createValidate.getMobile());
        systemAdminCreateValidate.setNickname(createValidate.getName());
        systemAdminCreateValidate.setDeptIds(model.getId());
        systemAdminCreateValidate.setRoleIds(10L);
        systemAdminCreateValidate.setPassword("rt123456!");
        iSystemAuthAdminService.add(systemAdminCreateValidate);
    }

    @Transactional
    @Override
    public void addCP(SystemDeptCreateValidate createValidate) {
        SystemAuthDept model = new SystemAuthDept();
        if (!Objects.isNull(createValidate.getPid())){
            model.setPid(createValidate.getPid());
        }else {
            model.setPid(1L);
        }
        model.setName(createValidate.getName());
        model.setDuty(createValidate.getDuty());
        model.setMobile(createValidate.getMobile());
        model.setSort(createValidate.getSort());
        model.setType(2);
        model.setIsStop(createValidate.getIsStop());
        systemAuthDeptMapper.insert(model);
        SystemAuthDept pDept;
        if (Objects.isNull(model.getPid())){
            pDept = systemAuthDeptMapper.selectById(1);
        }else {
            pDept = systemAuthDeptMapper.selectById(model.getPid());
        }
        model.setDeptCode(pDept.getDeptCode()+ "," + model.getId().toString());
        systemAuthDeptMapper.updateById(model);
        //将CP负责人添加成企业负责人
        SystemAdminCreateValidate systemAdminCreateValidate=new SystemAdminCreateValidate();
        systemAdminCreateValidate.setUsername(createValidate.getMobile());
        systemAdminCreateValidate.setNickname(createValidate.getName());
        systemAdminCreateValidate.setDeptIds(model.getId());
        systemAdminCreateValidate.setRoleIds(11L);
        systemAdminCreateValidate.setPassword("rt123456!");
        iSystemAuthAdminService.add(systemAdminCreateValidate);
    }

    /**
     * 部门编辑CP
     *
     * @author zyg
     * @param updateValidate 参数
     */
    @Transactional
    @Override
    public void edit(SystemDeptUpdateValidate updateValidate) {

        editSystemDept(updateValidate);
    }
    /**
     * 部门编辑CP
     *
     * @author zyg
     * @param updateValidate 参数
     */
    @Transactional
    @Override
    public void editCP(SystemDeptUpdateValidate updateValidate) {
        SystemAuthDept pDept = systemAuthDeptMapper.selectById(updateValidate.getPid());

        if(null!=pDept && !Objects.nonNull(pDept.getType())&&pDept.getType().equals(1)) {
            updateValidate.setType(2);
        }else if(null!=pDept &&  !Objects.nonNull(pDept.getType())&&pDept.getType().equals(2)) {
            updateValidate.setType(3);
        }else {
            updateValidate.setType(1);
        }
        editSystemDept(updateValidate);
    }
    /**
     * 部门编辑CP
     *
     * @author zyg
     * @param updateValidate 参数
     */
    @Transactional
    @Override
    public void editOP(SystemDeptUpdateValidate updateValidate) {
        SystemAuthDept pDept = systemAuthDeptMapper.selectById(updateValidate.getPid());

        if(null!=pDept && !Objects.nonNull(pDept.getType())&&pDept.getType().equals(1)) {
            updateValidate.setType(2);
        }else if(null!=pDept &&  !Objects.nonNull(pDept.getType())&&pDept.getType().equals(2)) {
            updateValidate.setType(3);
        }else {
            updateValidate.setType(1);
        }
        editSystemDept(updateValidate);
    }



    /**
     * 部门删除
     *
     * @author fzr
     * @param id 主键
     */
    @Transactional
    @Override
    public void del(Long id) {
        SystemAuthDept model = systemAuthDeptMapper.selectOne(
                new QueryWrapper<SystemAuthDept>()
                        .select("id,pid,name")
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "部门不存在");
        Assert.isFalse((model.getPid() == 0), "顶级部门不能删除");

        SystemAuthDept pModel = systemAuthDeptMapper.selectOne(
                new QueryWrapper<SystemAuthDept>()
                        .select("id,pid,name")
                        .eq("pid", id)
                        .last("limit 1"));

        Assert.isNull(pModel, "请先删除子级部门");

        SystemAuthAdmin systemAuthAdmin = systemAuthAdminMapper.selectOne(new QueryWrapper<SystemAuthAdmin>()
                .select("id,nickname")
                .eq("dept_ids", id)
                .eq("is_delete", 0)
                .last("limit 1"));

        Assert.isNull(systemAuthAdmin, "该部门已被管理员使用,请先移除");

        systemAuthDeptMapper.deleteById(model);
    }

    @Override
    public Boolean isExist(Long merchantId) {
        LambdaQueryWrapper<SystemAuthDept> systemAuthDeptLq=new LambdaQueryWrapper<>();
        systemAuthDeptLq.eq(SystemAuthDept::getId,merchantId);
        return systemAuthDeptMapper.exists(systemAuthDeptLq);
    }

    private SystemAuthDeptVo generateSystemAuthDeptVo(  SystemAuthDeptVo parentVo) {
        QueryWrapper<SystemAuthDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",parentVo.getId());
        queryWrapper.orderByDesc(Arrays.asList("sort", "id"));
        List<SystemAuthDept> childD = systemAuthDeptMapper.selectList(queryWrapper);
        if(childD!=null && !childD.isEmpty()){
            List<SystemAuthDeptVo> list = childD.stream().map(dept -> {
                        SystemAuthDeptVo systemAuthDeptVo1 =  new SystemAuthDeptVo();
                        BeanUtils.copyProperties(dept,systemAuthDeptVo1);
                        generateSystemAuthDeptVo(systemAuthDeptVo1);
                        return  systemAuthDeptVo1;
                    })
                    .collect(Collectors.toList());
            parentVo.setChildren(list);
        }
        return  parentVo;
    }

    private void editSystemDept(SystemDeptUpdateValidate updateValidate) {
        SystemAuthDept model = systemAuthDeptMapper.selectOne(
                new QueryWrapper<SystemAuthDept>()
                        .select(SystemAuthDept.class, info ->
                                !"is_delete".equals(info.getColumn()) &&
                                        !"delete_time".equals(info.getColumn()))
                        .eq("id", updateValidate.getId())
                        .last("limit 1"));

        Assert.notNull(model, "部门不存在");
        Assert.isFalse((model.getPid().equals(0L) && updateValidate.getPid()>0), "顶级部门不能修改上级");
        Assert.isFalse(updateValidate.getId().equals(updateValidate.getPid()), "上级部门不能是自己");

        SystemAuthDept pDept = systemAuthDeptMapper.selectById(model.getPid());
        model.setDeptCode(pDept.getDeptCode()+ "," + model.getId().toString());
        if(pDept.getType().equals(1)){
            model.setModel(updateValidate.getModel());
        }

        model.setPid(updateValidate.getPid());
        model.setName(updateValidate.getName());
        model.setDuty(updateValidate.getDuty());
        model.setMobile(updateValidate.getMobile());
        model.setSort(updateValidate.getSort());
        model.setIsStop(updateValidate.getIsStop());
        model.setType(updateValidate.getType());
        systemAuthDeptMapper.updateById(model);
    }
}
